package com.zsy.utils;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teaopenapi.models.Config;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.profile.DefaultProfile;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import com.aliyuncs.http.MethodType;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.exceptions.ClientException;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;


@Slf4j
@Component
public class SendCode {
    @Autowired
    private  RedisTemplate<String,Object> redisTemplate;

    private static final String ACCESS_KEY_ID = "LTAI5tMb8DZLism2yVDZ9eo7";//AccessKey自己账号的
    private static final String ACCESS_KEY_SECRET = "z6vSfUkq3YkJDuTeqKUh4Y0pE4tOLm";
    private static final String ENDPOINT = "dysmsapi.aliyuncs.com";//固定死
    private static final String SIGNNAME = "青云管理系统";//签名名称
    private static final String TCODE = "SMS_476770772";//模版的编号


    public  Boolean sendSms(String phoneNumbers) throws Exception {
        String code = RandomUtil.generateNumericCaptcha(5);
        HashMap<String, Object> map = new HashMap<>();
        map.put("code",code);
        log.info("验证码为：{}",code);
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", ACCESS_KEY_ID, ACCESS_KEY_SECRET);
        IAcsClient defaultAcsClient = new DefaultAcsClient(profile);

        CommonRequest commonRequest = new CommonRequest();
        commonRequest.setSysMethod(MethodType.POST);
        commonRequest.setSysDomain("dysmsapi.aliyuncs.com");
        commonRequest.setSysVersion("2017-05-25");
        commonRequest.setSysAction("SendSms");

        commonRequest.putQueryParameter("PhoneNumbers", phoneNumbers);
        commonRequest.putQueryParameter("SignName", SIGNNAME);
        commonRequest.putQueryParameter("TemplateCode", TCODE);
        commonRequest.putQueryParameter("TemplateParam", JSONObject.toJSONString(map));

        try {
            CommonResponse commonResponse = defaultAcsClient.getCommonResponse(commonRequest);
            System.out.println(commonResponse.getData());
            redisTemplate.opsForValue().set("code:" + phoneNumbers, code, 5, TimeUnit.MINUTES);
            return commonResponse.getHttpResponse().isSuccess();
        }catch (ServerException e){
            e.printStackTrace();
        }catch (ClientException e){
            e.printStackTrace();
        }
        return false;
    }
}
